﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.IO.Compression;

namespace WindowsFormsApplication24
{
    public partial class Form1 : Form
    {
        private class CookieInfo
        {
            public string Name { get; set; }
            public string Value { get; set; }
        }
        List<CookieInfo> m_cookielist = new List<CookieInfo>();

        public Form1()
        {
            InitializeComponent();

            webBrowser1.ScriptErrorsSuppressed = true;
            //webBrowser1.Navigate("http://tieba.baidu.com/p/4229379893");
            //webBrowser1.Navigate("http://tieba.baidu.com");
            webBrowser1.Navigate("https://passport.baidu.com");
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        public string SendHttpRequest(string url, string method, ref string setcookie, string cookie = "", string ContentType = "", string Referer = "", string Data = "", bool KeepAlive = false, bool Ajax = false, Dictionary<string, string> Head = null)
        {
            string result = "";
            HttpWebRequest req = null;
            HttpWebResponse rep = null;
            Encoding encoding = Encoding.Default;
            try
            {
                req = (HttpWebRequest)HttpWebRequest.Create(url);
                req.Headers["Accept-Encoding"] = "gzip, deflate";
                if (Ajax)
                    req.Headers["X-Requested-With"] = "XMLHttpRequest";
                if (Head != null)
                {
                    foreach (var kv in Head)
                        req.Headers[kv.Key] = kv.Value;
                }
                if (!string.IsNullOrEmpty(ContentType))
                    req.ContentType = ContentType;

                if (!string.IsNullOrEmpty(cookie))
                    req.Headers["Cookie"] = cookie;
                req.Method = method;
                if (req.Method == "POST")
                {
                    if (!string.IsNullOrEmpty(Data))
                    {
                        using (var sw = req.GetRequestStream())
                        {
                            byte[] sdata = Encoding.UTF8.GetBytes(Data);
                            sw.Write(sdata, 0, sdata.Length);
                        }
                    }
                }
                if (!string.IsNullOrEmpty(ContentType))
                    req.ContentType = ContentType;
                if (!string.IsNullOrEmpty(Referer))
                    req.Referer = Referer;//"http://www.baokuanyi.com/shop"

                req.Method = method;
                req.KeepAlive = KeepAlive;
                req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36";
                req.Timeout = 5 * 1000;
                req.AllowAutoRedirect = true;

                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(delegate { return true; });
                rep = (HttpWebResponse)req.GetResponse();
                setcookie = rep.Headers["Set-Cookie"];

                if (rep.ContentType != null)
                {
                    string contenttype = rep.ContentType.ToLower();
                    if (contenttype.IndexOf("utf-8") != -1)
                        encoding = Encoding.UTF8;
                }
                if (rep.ContentEncoding == "gzip")
                {
                    using (GZipStream gzip = new System.IO.Compression.GZipStream(rep.GetResponseStream(), CompressionMode.Decompress))
                    {
                        using (StreamReader sr = new StreamReader(gzip, encoding))
                        {
                            result = sr.ReadToEnd();
                        }
                    }
                }
                else if (rep.ContentEncoding == "deflate")
                {
                    using (DeflateStream gzip = new DeflateStream(rep.GetResponseStream(), CompressionMode.Decompress))
                    {
                        using (StreamReader sr = new StreamReader(gzip, encoding))
                        {
                            result = sr.ReadToEnd();
                        }
                    }
                }
                else
                {
                    using (StreamReader sr = new StreamReader(rep.GetResponseStream(), encoding))
                    {
                        result = sr.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (rep != null)
                {
                    rep.Close();
                    rep = null;
                }
                if (req != null)
                {
                    req.Abort();
                    req = null;
                }
            }
            return result;
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (e.Url.ToString().IndexOf("https://passport.baidu.com/center") != -1)
            {
                webBrowser1.Navigate("http://tieba.baidu.com");
            }
        }

        private void AddToCookieList(string cookie)
        {
            string[] items = cookie.Split(';');
            foreach (string item in items)
            {
                if (string.IsNullOrEmpty(item))
                    continue;
                string[] namevalues = item.Split('=');
                if (namevalues.Length >= 2)
                {
                    var info = new CookieInfo() { Name = namevalues[0].Trim(), Value = namevalues[1] };
                    var findinfo = m_cookielist.Find(s => s.Name == info.Name);
                    if (findinfo != null)
                        continue;
                    for (int i = 2; i < namevalues.Length; ++i)
                        info.Value += "=" + namevalues[i];
                    m_cookielist.Add(info);
                }
            }
        }

        private string CookieListToStr()
        {
            string cookie = "";
            CookieInfo findinfo = null;
            findinfo = m_cookielist.Find(s => s.Name == "TIEBA_USERTYPE");
            if (findinfo != null) cookie += findinfo.Name + "=" + findinfo.Value + ";";

            findinfo = m_cookielist.Find(s => s.Name == "TIEBAUID");
            if (findinfo != null) cookie += findinfo.Name + "=" + findinfo.Value + ";";

            findinfo = m_cookielist.Find(s => s.Name == "wise_device");
            if (findinfo != null) cookie += findinfo.Name + "=" + findinfo.Value + ";";

            //findinfo = m_cookielist.Find(s => s.Name == "bdshare_firstime");
            //if (findinfo != null) cookie += findinfo.Name + "=" + findinfo.Value + ";";

            findinfo = m_cookielist.Find(s => s.Name == "BAIDUID");
            if (findinfo != null) cookie += findinfo.Name + "=" + findinfo.Value + ";";

            findinfo = m_cookielist.Find(s => s.Name == "BDUSS");
            if (findinfo != null) cookie += findinfo.Name + "=" + findinfo.Value + ";";

            findinfo = m_cookielist.Find(s => s.Name == "TOPMSG");
            if (findinfo != null) cookie += findinfo.Name + "=" + findinfo.Value + ";";

            findinfo = m_cookielist.Find(s => s.Name == "BIDUPSID");
            if (findinfo != null) cookie += findinfo.Name + "=" + findinfo.Value + ";";

            findinfo = m_cookielist.Find(s => s.Name == "PSTM");
            if (findinfo != null) cookie += findinfo.Name + "=" + findinfo.Value + ";";
            
            return cookie;
        }

        private void 获得CookieToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            string url = "http://tieba.baidu.com/p/4229557968";
            string cookie = FullWebBrowserCookie.GetCookieInternal(new Uri(url), false);
            if (!string.IsNullOrEmpty(cookie))
                AddToCookieList(cookie);

            HtmlElement script = webBrowser1.Document.CreateElement("script");
            script.SetAttribute("type", "text/javascript");
            script.SetAttribute("text", "function GetCookies(){return document.cookie;} function GetUserId(){return PageData.user.user_id;}");
            webBrowser1.Document.Body.AppendChild(script);
            string cookie2 = Convert.ToString(webBrowser1.Document.InvokeScript("GetCookies"));
            if (!string.IsNullOrEmpty(cookie2))
                AddToCookieList(cookie2);

            string userid = Convert.ToString(webBrowser1.Document.InvokeScript("GetUserId"));
            if (!string.IsNullOrEmpty(userid))
                AddToCookieList("LONGID=" + userid + ";");
            AddToCookieList("wise_device=0;");
            
            DataTable dt = m_cookielist.ToDataSet().Tables[0];            
            CommonClass.UpdateGetDataStatus(dataGridView1);
            this.dataGridView1.DataSource = dt;
            this.toolStripStatusLabel1.Text = "记录数：" + dt.Rows.Count;
            tabControl1.SelectedIndex = 1;
        }

        private void 设置使用最高版本IE加载页面ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CommonClass.EnableIE9();
        }

        private void 显示IE版本ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show(webBrowser1.Version.ToString());
        }

        private void 发送请求ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string TieBaName = "魔天记";
            TieBaName = System.Web.HttpUtility.UrlEncode(TieBaName).ToUpper();
            string TieBaId = "4295466";//相应贴吧页面获取 静态
            string TieId = "4229379893";//相应贴吧页面获取 静态

            string tbs = "2672cf0e0716130c1450943170";//相应贴吧页面获取 动态

            HtmlElement script = webBrowser1.Document.CreateElement("script");
            script.SetAttribute("type", "text/javascript");
            script.SetAttribute("text", "function Gettbs(){return PageData.tbs;}");
            webBrowser1.Document.Body.AppendChild(script);
            tbs = Convert.ToString(webBrowser1.Document.InvokeScript("Gettbs"));

            string content = "发帖内容";//发帖内容
            content = System.Web.HttpUtility.UrlEncode(content).ToUpper();
            string files = "[]";
            files = System.Web.HttpUtility.UrlEncode(files).ToUpper();

            string Data = 
            //"ie=utf-8&kw=%E9%AD%94%E5%A4%A9%E8%AE%B0&fid=4295466&tid=4229379893&vcode_md5=&floor_num=170&rich_text=1&tbs=e825b7fda65999e51451006939&content=%E6%B0%B4%E6%B0%B4&files=%5B%5D&__type__=reply";
              "ie=utf-8&kw=" + TieBaName + "&fid=" + TieBaId + "&tid=" + TieId + "&vcode_md5=&floor_num=130&rich_text=1&tbs=" + tbs + "&content=" + content + "&files=" + files + "&__type__=reply";

            string Referer = "http://tieba.baidu.com/p/" + TieId;
            string Url = "http://tieba.baidu.com/f/commit/post/add";
            string Result = "";
            string setcookie = "", cookie = "";
            //AddToCookieList("TIEBA_USERTYPE=7c2a31580033f684c8f7d399; TIEBAUID=edaa8f295102483c80e780d2; BDUSS=EZDM1ljZHg5Skxud2d6RG82YzJOQ1N6V2g0NnVaVTQ0Mm1kaEVBMy0wemg3NkpXQVFBQUFBJCQAAAAAAAAAAAEAAAA2GPcDcXEyNzQyNDYzNDUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOFie1bhYntWR; PSTM=1450929138; BIDUPSID=033C2DB60B7E35A4ECA1AF3A5C1DEDC3; BAIDUID=231877D1FF35CF775650BF9E0218AF59:FG=1; wise_device=0; LONGID=66525238");
            //foreach (var info in m_cookielist)
            //    if (info.Name.Trim() != "TOPMSG")
            //    cookie += info.Name + "=" + info.Value + ";";
            //cookie = cookie.Substring(0, cookie.Length - 1);
            cookie = CookieListToStr();
            tabControl1.SelectedIndex = 2;
            Result = SendHttpRequest(Url, "POST", ref setcookie, cookie, "application/x-www-form-urlencoded; charset=UTF-8", Referer, Data, false, true);
            if (Result.Length > 0)
            {
                Result = System.Web.HttpUtility.HtmlDecode(Result).Trim();
                richTextBox1.AppendText(Result);
                PostResultInfo resultinfo = JsonHelper.StringToJson<PostResultInfo>(Result);
                if (resultinfo.err_code == 0)
                {
                    MessageBox.Show("发帖成功！");
                }
            }
        }

        private void 载入ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate("http://tieba.baidu.com");
            //webBrowser1.Navigate("https://passport.baidu.com");
        }
    }
}
